home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2007 January, February, March & April
/
Chip-Cover-CD-2007-02.iso
/
Pakiet bezpieczenstwa
/
mini Pentoo LiveCD 2006.1
/
mpentoo-2006.1.iso
/
livecd.squashfs
/
usr
/
lib
/
python2.4
/
site-packages
/
impacket
/
nmb.pyc
(
.txt
)
< prev
next >
Wrap
Python Compiled Bytecode
|
2006-06-30
|
27KB
|
899 lines
# Source Generated with Decompyle++
# File: in.pyc (Python 2.4)
import os
import sys
import socket
import string
import re
import select
import errno
from random import randint
from struct import *
CVS_REVISION = '$Revision: 1.4 $'
INADDR_ANY = ''
BROADCAST_ADDR = '<broadcast>'
NETBIOS_NS_PORT = 137
NETBIOS_SESSION_PORT = 139
SMB_SESSION_PORT = 445
NODE_B = 0
NODE_P = 8192
NODE_M = 16384
NODE_RESERVED = 24576
NODE_GROUP = 32768
NODE_UNIQUE = 0
TYPE_UNKNOWN = 1
TYPE_WORKSTATION = 0
TYPE_CLIENT = 3
TYPE_SERVER = 32
TYPE_DOMAIN_MASTER = 27
TYPE_MASTER_BROWSER = 29
TYPE_BROWSER = 30
TYPE_NETDDE = 31
OPCODE_QUERY = 0
OPCODE_REGISTRATION = 5
OPCODE_RELEASE = 6
OPCODE_WACK = 7
OPCODE_REFRESH = 8
OPCODE_REQUEST = 0
OPCODE_RESPONSE = 16
NM_FLAGS_BROADCAST = 1
NM_FLAGS_UNICAST = 0
NM_FLAGS_RA = 8
NM_FLAGS_RD = 16
NM_FLAGS_TC = 32
NM_FLAGS_AA = 64
QUESTION_TYPE_NB = 32
QUESTION_TYPE_NBSTAT = 33
QUESTION_CLASS_IN = 1
RR_TYPE_A = 1
RR_TYPE_NS = 2
RR_TYPE_NULL = 10
RR_TYPE_NB = 32
RR_TYPE_NBSTAT = 33
RR_CLASS_IN = 1
RCODE_FMT_ERR = 1
RCODE_SRV_ERR = 2
RCODE_IMP_ERR = 4
RCODE_RFS_ERR = 5
RCODE_ACT_ERR = 6
RCODE_CFT_ERR = 7
NAME_FLAGS_PRM = 512
NAME_FLAGS_ACT = 1024
NAME_FLAG_CNF = 2048
NAME_FLAG_DRG = 4096
NAME_TYPES = {
TYPE_UNKNOWN: 'Unknown',
TYPE_WORKSTATION: 'Workstation',
TYPE_CLIENT: 'Client',
TYPE_SERVER: 'Server',
TYPE_MASTER_BROWSER: 'Master Browser',
TYPE_BROWSER: 'Browser Server',
TYPE_DOMAIN_MASTER: 'Domain Master',
TYPE_NETDDE: 'NetDDE Server' }
NETBIOS_SESSION_MESSAGE = 0
NETBIOS_SESSION_REQUEST = 129
NETBIOS_SESSION_POSITIVE_RESPONSE = 130
NETBIOS_SESSION_NEGATIVE_RESPONSE = 131
NETBIOS_SESSION_RETARGET_RESPONSE = 132
NETBIOS_SESSION_KEEP_ALIVE = 133
def strerror(errclass, errcode):
if errclass == ERRCLASS_OS:
return ('OS Error', os.strerror(errcode))
elif errclass == ERRCLASS_QUERY:
return ('Query Error', QUERY_ERRORS.get(errcode, 'Unknown error'))
elif errclass == ERRCLASS_SESSION:
return ('Session Error', SESSION_ERRORS.get(errcode, 'Unknown error'))
else:
return ('Unknown Error Class', 'Unknown Error')
class NetBIOSError(Exception):
pass
class NetBIOSTimeout(Exception):
def __init__(self, message = 'The NETBIOS connection with the remote host timed out.'):
Exception.__init__(self, message)
class NBResourceRecord:
def __init__(self, data = 0):
self._data = data
try:
if self._data:
self.rr_name = re.split('\x00', data)[0]
offset = len(self.rr_name) + 1
self.rr_type = unpack('>H', self._data[offset:offset + 2])[0]
self.rr_class = unpack('>H', self._data[offset + 2:offset + 4])[0]
self.ttl = unpack('>L', self._data[offset + 4:offset + 8])[0]
self.rdlength = unpack('>H', self._data[offset + 8:offset + 10])[0]
self.rdata = data[offset + 10:self.rdlength]
offset = self.rdlength - 2
self.unit_id = data[offset:offset + 6]
else:
self.rr_name = ''
self.rr_type = 0
self.rr_class = 0
self.ttl = 0
self.rdlength = 0
self.rdata = ''
self.unit_id = ''
except Exception:
e = None
raise NetBIOSError('Wrong packet format ')
def set_rr_name(self, name):
self.rr_name = name
def set_rr_type(self, name):
self.rr_type = name
def set_rr_class(self, cl):
self_rr_class = cl
def set_ttl(self, ttl):
self.ttl = ttl
def set_rdata(self, rdata):
self.rdata = rdata
self.rdlength = len(rdata)
def get_unit_id(self):
return self.unit_id
def get_rr_name(self):
return self.rr_name
def get_rr_class(self):
return self.rr_class
def get_ttl(self):
return self.ttl
def get_rdlength(self):
return self.rdlength
def get_rdata(self):
return self.rdata
def rawData(self):
return self.rr_name + pack('!HHLH', self.rr_type, self.rr_class, self.ttl, self.rdlength) + self.rdata
class NBNodeStatusResponse(NBResourceRecord):
def __init__(self, data = 0):
NBResourceRecord.__init__(self, data)
self.num_names = 0
self.node_names = []
self.statstics = ''
self.mac = '00-00-00-00-00-00'
try:
if data:
self._data = self.get_rdata()
self.num_names = unpack('>B', self._data[:1])[0]
offset = 1
for i in range(0, self.num_names):
name = self._data[offset:offset + 15]
(type, flags) = unpack('>BH', self._data[offset + 15:offset + 18])
offset += 18
self.node_names.append(NBNodeEntry(name, type, flags))
self.set_mac_in_hexa(self.get_unit_id())
except Exception:
e = None
raise NetBIOSError('Wrong packet format ')
def set_mac_in_hexa(self, data):
data_aux = ''
for d in data:
if data_aux == '':
data_aux = '%02x' % ord(d)
continue
data_aux += '-%02x' % ord(d)
self.mac = string.upper(data_aux)
def get_num_names(self):
return self.num_names
def get_mac(self):
return self.mac
def set_num_names(self, num):
self.num_names = num
def get_node_names(self):
return self.node_names
def add_node_name(self, node_names):
self.node_names.append(node_names)
self.num_names += 1
def rawData(self):
res = pack('!B', self.num_names)
for i in range(0, self.num_names):
res += self.node_names[i].rawData()
class NBPositiveNameQueryResponse(NBResourceRecord):
def __init__(self, data = 0):
NBResourceRecord.__init__(self, data)
self.add_entries = []
if data:
self._data = self.get_rdata()
class NetBIOSPacket:
''' This is a packet as defined in RFC 1002 '''
def __init__(self, data = 0):
self.name_trn_id = 0
self.opcode = 0
self.nm_flags = 0
self.rcode = 0
self.qdcount = 0
self.ancount = 0
self.nscount = 0
self.arcount = 0
self.questions = ''
self.answers = ''
if data == 0:
self._data = ''
else:
try:
self._data = data
self.opcode = ord(data[2]) >> 3
self.nm_flags = (ord(data[2]) & 3) << 4 | (ord(data[3]) & 240) >> 4
self.name_trn_id = unpack('>H', self._data[:2])[0]
self.rcode = ord(data[3]) & 15
self.qdcount = unpack('>H', self._data[4:6])[0]
self.ancount = unpack('>H', self._data[6:8])[0]
self.nscount = unpack('>H', self._data[8:10])[0]
self.arcount = unpack('>H', self._data[10:12])[0]
self.answers = self._data[12:]
except Exception:
e = None
raise NetBIOSError('Wrong packet format ')
def set_opcode(self, opcode):
self.opcode = opcode
def set_trn_id(self, trn):
self.name_trn_id = trn
def set_nm_flags(self, nm_flags):
self.nm_flags = nm_flags
def set_rcode(self, rcode):
self.rcode = rcode
def addQuestion(self, question, qtype, qclass):
self.qdcount = self.qdcount + 1
self.questions += question + pack('!HH', qtype, qclass)
def get_trn_id(self):
return self.name_trn_id
def get_rcode(self):
return self.rcode
def get_nm_flags(self):
return self.name_trn_id
def get_opcode(self):
return self.opcode
def get_qdcount(self):
return self.qdcount
def get_ancount(self):
return self.ancount
def get_nscount(self):
return self.nscount
def get_arcount(self):
return self.arcount
def rawData(self):
secondWord = self.opcode << 11
secondWord = secondWord | self.nm_flags << 4
secondWord = secondWord | self.rcode
data = pack('!HHHHHH', self.name_trn_id, secondWord, self.qdcount, self.ancount, self.nscount, self.arcount) + self.questions + self.answers
return data
def get_answers(self):
return self.answers
class NBHostEntry:
def __init__(self, nbname, nametype, ip):
self._NBHostEntry__nbname = nbname
self._NBHostEntry__nametype = nametype
self._NBHostEntry__ip = ip
def get_nbname(self):
return self._NBHostEntry__nbname
def get_nametype(self):
return self._NBHostEntry__nametype
def get_ip(self):
return self._NBHostEntry__ip
def __repr__(self):
return '<NBHostEntry instance: NBname="' + self._NBHostEntry__nbname + '", IP="' + self._NBHostEntry__ip + '">'
class NBNodeEntry:
def __init__(self, nbname, nametype, flags):
self._NBNodeEntry__nbname = string.ljust(nbname, 17)
self._NBNodeEntry__nametype = nametype
self._NBNodeEntry__flags = flags
self._NBNodeEntry__isgroup = flags & 32768
self._NBNodeEntry__nodetype = flags & 24576
self._NBNodeEntry__deleting = flags & 4096
self._NBNodeEntry__isconflict = flags & 2048
self._NBNodeEntry__isactive = flags & 1024
self._NBNodeEntry__ispermanent = flags & 512
def get_nbname(self):
return self._NBNodeEntry__nbname
def get_nametype(self):
return self._NBNodeEntry__nametype
def is_group(self):
return self._NBNodeEntry__isgroup
def get_nodetype(self):
return self._NBNodeEntry__nodetype
def is_deleting(self):
return self._NBNodeEntry__deleting
def is_conflict(self):
return self._NBNodeEntry__isconflict
def is_active(self):
return self._NBNodeEntry__isactive
def is_permanent(self):
return self._NBNodeEntry__ispermanent
def set_nbname(self, name):
self._NBNodeEntry__nbname = string.ljust(name, 17)
def set_nametype(self, type):
self._NBNodeEntry__nametype = type
def set_flags(self, flags):
self._NBNodeEntry__flags = flags
def __repr__(self):
s = '<NBNodeEntry instance: NBname="' + self._NBNodeEntry__nbname + '" NameType="' + NAME_TYPES[self._NBNodeEntry__nametype] + '"'
if self._NBNodeEntry__isactive:
s = s + ' ACTIVE'
if self._NBNodeEntry__isgroup:
s = s + ' GROUP'
if self._NBNodeEntry__isconflict:
s = s + ' CONFLICT'
if self._NBNodeEntry__deleting:
s = s + ' DELETING'
return s
def rawData(self):
return self._NBNodeEntry__nbname + pack('!BH', self._NBNodeEntry__nametype, self._NBNodeEntry__flags)
class NetBIOS:
def __init__(self, servport = NETBIOS_NS_PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
has_bind = 1
for i in range(0, 10):
try:
s.bind((INADDR_ANY, randint(10000, 60000)))
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
has_bind = 1
continue
except socket.error:
ex = None
continue
if not has_bind:
raise NetBIOSError, ('Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN)
self._NetBIOS__sock = s
self._NetBIOS__servport = NETBIOS_NS_PORT
self._NetBIOS__nameserver = None
self._NetBIOS__broadcastaddr = BROADCAST_ADDR
self.mac = '00-00-00-00-00-00'
def set_nameserver(self, nameserver):
self._NetBIOS__nameserver = nameserver
def get_nameserver(self):
return self._NetBIOS__nameserver
def set_broadcastaddr(self, broadcastaddr):
self._NetBIOS__broadcastaddr = broadcastaddr
def get_broadcastaddr(self):
return self._NetBIOS__broadcastaddr
def gethostbyname(self, nbname, type = TYPE_WORKSTATION, scope = None, timeout = 1):
return self._NetBIOS__queryname(nbname, self._NetBIOS__nameserver, type, scope, timeout)
def getnodestatus(self, nbname, destaddr = None, type = TYPE_WORKSTATION, scope = None, timeout = 1):
if destaddr:
return self._NetBIOS__querynodestatus(nbname, destaddr, type, scope, timeout)
else:
return self._NetBIOS__querynodestatus(nbname, self._NetBIOS__nameserver, type, scope, timeout)
def getmacaddress(self):
return self.mac
def __queryname(self, nbname, destaddr, type, scope, timeout):
netbios_name = string.upper(nbname)
trn_id = randint(1, 32000)
p = NetBIOSPacket()
p.set_trn_id(trn_id)
netbios_name = string.upper(nbname)
qn_label = encode_name(netbios_name, type, scope)
p.addQuestion(qn_label, QUESTION_TYPE_NB, QUESTION_CLASS_IN)
qn_label = encode_name(netbios_name, type, scope)
if not destaddr:
p.set_nm_flags(NM_FLAGS_BROADCAST)
destaddr = self._NetBIOS__broadcastaddr
wildcard_query = netbios_name == '*'
req = p.rawData()
self._NetBIOS__sock.sendto(req, 0, (destaddr, self._NetBIOS__servport))
addrs = []
tries = 3
while None:
try:
(ready, _, _) = select.select([
self._NetBIOS__sock.fileno()], [], [], timeout)
if not ready:
if tries and not wildcard_query:
self._NetBIOS__sock.sendto(req, 0, (destaddr, self._NetBIOS__servport))
tries = tries - 1
elif wildcard_query:
return addrs
else:
raise NetBIOSTimeout
else:
(data, _) = self._NetBIOS__sock.recvfrom(65536, 0)
res = NetBIOSPacket(data)
if res.get_trn_id() == p.get_trn_id():
if res.get_rcode():
if res.get_rcode() == 3:
return None
else:
raise NetBIOSError, ('Negative name query response', ERRCLASS_QUERY, res.get_rcode())
answ = NBPositiveNameQueryResponse(res.get_answers())
if not wildcard_query:
return addrs
except select.error:
ready
ex = ready
if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN:
raise NetBIOSError, ('Error occurs while waiting for response', ERRCLASS_OS, ex[0])
ex[0] != errno.EAGAIN
except socket.error:
ex = None
continue
None<EXCEPTION MATCH>socket.error
return None
def __querynodestatus(self, nbname, destaddr, type, scope, timeout):
trn_id = randint(1, 32000)
p = NetBIOSPacket()
p.set_trn_id(trn_id)
netbios_name = string.upper(nbname)
qn_label = encode_name(netbios_name, type, scope)
p.addQuestion(qn_label, QUESTION_TYPE_NBSTAT, QUESTION_CLASS_IN)
if not destaddr:
p.set_nm_flags(NM_FLAGS_BROADCAST)
destaddr = self._NetBIOS__broadcastaddr
req = p.rawData()
tries = 3
while None:
try:
self._NetBIOS__sock.sendto(req, 0, (destaddr, self._NetBIOS__servport))
(ready, _, _) = select.select([
self._NetBIOS__sock.fileno()], [], [], timeout)
if not ready:
if tries:
tries = tries - 1
else:
raise NetBIOSTimeout
else:
try:
(data, _) = self._NetBIOS__sock.recvfrom(65536, 0)
except:
return None
res = NetBIOSPacket(data)
if res.get_trn_id() == p.get_trn_id():
if res.get_rcode():
if res.get_rcode() == 3:
return None
else:
raise NetBIOSError, ('Negative name query response', ERRCLASS_QUERY, res.get_rcode())
answ = NBNodeStatusResponse(res.get_answers())
self.mac = answ.get_mac()
return answ.get_node_names()
except select.error:
ready
ex = ready
if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN:
raise NetBIOSError, ('Error occurs while waiting for response', ERRCLASS_OS, ex[0])
ex[0] != errno.EAGAIN
except socket.error:
ex = None
continue
None<EXCEPTION MATCH>socket.error
return None
def encode_name(name, type, scope):
if name == '*':
name = name + '\x00' * 15
elif len(name) > 15:
name = name[:15] + chr(type)
else:
name = string.ljust(name, 15) + chr(type)
encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name)
if scope:
encoded_scope = ''
for s in string.split(scope, '.'):
encoded_scope = encoded_scope + chr(len(s)) + s
return encoded_name + encoded_scope + '\x00'
else:
return encoded_name + '\x00'
def _do_first_level_encoding(m):
s = ord(m.group(0))
return string.uppercase[s >> 4] + string.uppercase[s & 15]
def decode_name(name):
name_length = ord(name[0])
if not name_length == 32:
raise AssertionError
decoded_name = re.sub('..', _do_first_level_decoding, name[1:33])
if name[33] == '\x00':
return (34, decoded_name, '')
else:
decoded_domain = ''
offset = 34
while None:
domain_length = ord(name[offset])
if domain_length == 0:
break
decoded_domain = '.' + name[offset:offset + domain_length]
offset = offset + domain_length
return (offset + 1, decoded_name, decoded_domain)
def _do_first_level_decoding(m):
s = m.group(0)
return chr(ord(s[0]) - ord('A') << 4 | ord(s[1]) - ord('A'))
class NetBIOSSessionPacket:
def __init__(self, data = 0):
self.type = 0
self.flags = 0
self.length = 0
if data == 0:
self._trailer = ''
else:
try:
self.type = ord(data[0])
self.flags = ord(data[1])
self.length = unpack('!H', data[2:4])[0]
self._trailer = data[4:]
except:
raise NetBIOSError('Wrong packet format ')
def set_type(self, type):
self.type = type
def get_type(self):
return self.type
def rawData(self):
data = pack('!BBH', self.type, self.flags, self.length) + self._trailer
return data
def set_trailer(self, data):
self._trailer = data
self.length = len(data)
def get_length(self):
return self.length
def get_trailer(self):
return self._trailer
class NetBIOSSession:
def __init__(self, myname, remote_name, remote_host, remote_type = TYPE_SERVER, sess_port = NETBIOS_SESSION_PORT, timeout = None, local_type = TYPE_WORKSTATION):
if len(myname) > 15:
self._NetBIOSSession__myname = string.upper(myname[:15])
else:
self._NetBIOSSession__myname = string.upper(myname)
if not remote_name:
raise AssertionError
if len(remote_name) > 15:
self._NetBIOSSession__remote_name = string.upper(remote_name[:15])
else:
self._NetBIOSSession__remote_name = string.upper(remote_name)
self._NetBIOSSession__remote_host = remote_host
self._NetBIOSSession__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self._NetBIOSSession__sock.connect((remote_host, sess_port))
except socket.error:
ex = None
raise ex
if sess_port == NETBIOS_SESSION_PORT:
self._NetBIOSSession__request_session(remote_type, local_type, timeout)
def get_myname(self):
return self._NetBIOSSession__myname
def get_remote_host(self):
return self._NetBIOSSession__remote_host
def get_remote_name(self):
return self._NetBIOSSession__remote_name
def close(self):
self._NetBIOSSession__sock.close()
def send_packet(self, data):
p = NetBIOSSessionPacket()
p.set_type(NETBIOS_SESSION_MESSAGE)
p.set_trailer(data)
self._NetBIOSSession__sock.send(p.rawData())
def recv_packet(self, timeout = None):
data = self._NetBIOSSession__read(timeout)
return NetBIOSSessionPacket(data)
def __request_session(self, remote_type, local_type, timeout = None):
p = NetBIOSSessionPacket()
remote_name = encode_name(self._NetBIOSSession__remote_name, remote_type, '')
myname = encode_name(self._NetBIOSSession__myname, local_type, '')
p.set_type(NETBIOS_SESSION_REQUEST)
p.set_trailer(remote_name + myname)
self._NetBIOSSession__sock.send(p.rawData())
while None:
p = self.recv_packet(timeout)
if p.get_type() == NETBIOS_SESSION_NEGATIVE_RESPONSE:
raise NetBIOSError, ('Cannot request session', ERRCLASS_SESSION, ord(p.get_trailer()[0]))
continue
if p.get_type() == NETBIOS_SESSION_POSITIVE_RESPONSE:
break
continue
def __read(self, timeout = None):
read_len = 4
data = ''
while read_len > 0:
try:
(ready, _, _) = select.select([
self._NetBIOSSession__sock.fileno()], [], [], timeout)
if not ready:
raise NetBIOSTimeout
received = self._NetBIOSSession__sock.recv(read_len)
if len(received) == 0:
raise NetBIOSError, ('Error while reading from remote', ERRCLASS_OS, None)
data = data + received
read_len = 4 - len(data)
continue
except select.error:
ex = None
if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN:
raise NetBIOSError, ('Error occurs while reading from remote', ERRCLASS_OS, ex[0])
ex[0] != errno.EAGAIN
None<EXCEPTION MATCH>select.error
(type, flags, length) = unpack('>ccH', data)
if ord(flags) & 1:
length = length | 65536
read_len = length
data2 = ''
while read_len > 0:
try:
(ready, _, _) = select.select([
self._NetBIOSSession__sock.fileno()], [], [], timeout)
if not ready:
raise NetBIOSTimeout
received = self._NetBIOSSession__sock.recv(read_len)
if len(received) == 0:
raise NetBIOSError, ('Error while reading from remote', ERRCLASS_OS, None)
data2 = data2 + received
read_len = length - len(data2)
continue
except select.error:
ex = None
if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN:
raise NetBIOSError, ('Error while reading from remote', ERRCLASS_OS, ex[0])
ex[0] != errno.EAGAIN
None<EXCEPTION MATCH>select.error
return data + data2
def get_socket(self):
return self._NetBIOSSession__sock
ERRCLASS_QUERY = 0
ERRCLASS_SESSION = 240
ERRCLASS_OS = 255
QUERY_ERRORS = {
1: 'Request format error. Please file a bug report.',
2: 'Internal server error',
3: 'Name does not exist',
4: 'Unsupported request',
5: 'Request refused' }
SESSION_ERRORS = {
128: 'Not listening on called name',
129: 'Not listening for calling name',
130: 'Called name not present',
131: 'Sufficient resources',
143: 'Unspecified error' }
def main():
print
if __name__ == '__main__':
main()